<?php
/*
 * @Author: 哲学家乔布斯 <wuyangii@qq.com>
 * @Date: 2022-10-20 21:41:37
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-11-07 22:37:15
 * @Descripttion: 商品管理
 */
namespace app\agent\controller\system;
use think\Db;
class Order extends \app\agent\controller\Common
{
    public function index(){
    
        return view();
    }

    public function list(){
        $limit = request()->param('limit') ?? 15;
        $page = request()->param('page');
        $page = $page ? ($page - 1) * $limit : 0;
        $search = request()->param();
       
        $query = (new \app\common\model\AgentOrder())
                ->where(['agent_id' => $this->userInfo['id']]);

        isset($search['goods_title']) && $search['goods_title'] != "" ? $query->where("title like '%{$search['goods_title']}%'") : '';
        $query->order("id desc");

        $list = $query->limit($page, $limit)->append(['addtime_text','state_text'])->select();
        $count = $query->count();
        return self::successResult('',$list,$count);
    }

    public function add(){
     
        if (request()->isPost()) {
            $info = request()->param('info');
            $validate = new \app\common\validate\AgentOrder();
            $result = $validate->scene("add")->check($info);
            if ($result === false) {
                return self::errorResult($validate->getError());
            }
            
            Db::startTrans();
            try{
                $message = "订单创建失败,请重试";
                $process = true;
                $goods_sku = (new \app\common\model\GoodsSku())->where(['id' => $info['goods_sku_id']])->find();
                $goods = (new \app\common\model\Goods())->where(['id' => $goods_sku['goods_id']])->find();
                // if($goods_sku['money'] > $info['x_money']){
                //     $message = "销售价格不能小于商品原价！！！";
                //     $process = false;
                // }
                if($goods_sku['stock'] < $info['num']){
                    $message = "超出总商品库存了!!!";
                    $process = false;
                }
                $info['goods_id'] = $goods_sku['goods_id'];
                $info['agent_id'] = $this->userInfo['id'];
                unset($info['cate_id']);
 
                $on = 'A'.date('YmdHis') . rand(1000, 9999);
                $num = $info['num'] == 0 ? $goods['stock'] : $info['num'];
                $row = (new \app\common\model\AgentOrder())->insert([
                    'on' => $on,
                    'goods_id' => $info['goods_id'],
                    'goods_sku_id' => $info['goods_sku_id'],
                    'agent_id' => $this->userInfo['id'],
                    'state' => 0,
                    'addtime' => time(),
                    'num' => $num,
                    'money' => $goods_sku['money'],
                    'x_money' => $info['x_money'],
                    'goods_title' => $goods['title'],
                    'goods_sku_title' => $goods_sku['sku_title'],
                    'title' => $goods['title'].$goods_sku['sku_title']
                ]);
                if(!$row){
                    $message = "创建订单失败";
                    $process = false;
                }
                #查询商品是否存在
                $agent_goods_sku = (new \app\common\model\AgentGoodsSku())->where([
                    'goods_id' => $info['goods_id'],
                    'goods_sku_id' => $info['goods_sku_id'],
                    'agent_id' => $this->userInfo['id'],
                ])->find();
                #修改代理商库存
                if(!$agent_goods_sku){
                    $row = (new \app\common\model\AgentGoodsSku())->insertGetId([
                        'goods_id' => $info['goods_id'],
                        'goods_sku_id' => $info['goods_sku_id'],
                        'money_cost' => $goods_sku['money'],
                        'money_primary' => $goods_sku['money']+$info['x_money']+(($goods_sku['money']+$info['x_money']) * (rand(25,30)/100)),
                        'money' => $goods_sku['money']+$info['x_money'],
                        // 'stock' => $num,
                        'agent_id' => $this->userInfo['id'],
                    ]);
                    if(!$row){
                        $message = "添加商品失败";
                        $process = false;
                    }
                }else{
                    // $row = (new \app\common\model\AgentGoodsSku())->where([
                    //     'stock' => $agent_goods_sku['stock'],
                    // ])->update([
                    //     'stock' => $agent_goods_sku['stock']+$num,
                    // ]);
                    // if(!$row){
                    //     $message = "修改商品库存失败";
                    //     $process = false;
                    // }
                }
                #修改总商品库存
                // $row = (new \app\common\model\GoodsSku())->where([
                //     'id' => $info['goods_sku_id'],
                //     'stock' => $goods_sku['stock']
                //     ])->update(['stock' => $goods_sku['stock']-$num]);
                // if(!$row){
                //     $message = "修改总商品库存失败";
                //     $process = false;
                // }

                if ($process !== false) {
                    Db::commit(); // 提交事务
                } else {
                    Db::rollback(); // 回滚事务
                }

            } catch (\Exception $e) {
                $process = false;
                $message = $e->getMessage();
                Db::rollback(); // 回滚事务
            }
            if ($process !== false) {
                return self::successResult("创建成功");
            } else {
                return self::errorResult($message);
            }
           
       
        } else {
            $cate = (new \app\common\model\GoodsCate())->lists();
            $this->assign("cate",$cate);
  
            return view();
        }

    }
    
   public function goods(){
        $limit = request()->param('limit') ?? 15;
        $page = request()->param('page');
        $page = $page ? ($page - 1) * $limit : 0;
        $search = request()->param();
    
        $query = (new \app\common\model\Goods())->where(['is_del' => 0]);

        isset($search['goods_title']) && $search['goods_title'] != "" ? $query->where("title like '%{$search['goods_title']}%'") : '';
        $query->order("id desc");
        $where = [];
        if(!empty($search['bus_id'])){
            $where['bus_id'] = $search['bus_id'];
        }
        $list = $query->limit($page, $limit)->where($where)->append(['cate_title'])->select();
        $count = $query->count();
        return self::successResult('',$list,$count);
    }
        
   public function goods_sku(){
        $limit = request()->param('limit') ?? 15;
        $page = request()->param('page');
        $page = $page ? ($page - 1) * $limit : 0;
        $search = request()->param();
        $query = (new \app\common\model\GoodsSku())
                ->alias("goods_sku")
                ->join("{$this->tdb}goods goods","goods.id = goods_sku.goods_id")
                ->field([
                    'goods_sku.id',
                    'goods_sku.money',
                    'goods_sku.sku_title',
                    'goods.img',
                    'goods.title',
                    'goods.introduce',
                    'goods.cate_id',
                    ])
                ->where(['is_del' => 0]);
        isset($search['title']) && $search['title'] != "" ? $query->where("title like '%{$search['title']}%'") : '';
        $query->order("goods_sku.id desc");
        $where = [];
        if(!empty($search['bus_id'])){
            $where['bus_id'] = $search['bus_id'];
        }
        $list = $query->limit($page, $limit)->where($where)
                ->append(['cate_title'])
                ->select();
        $count = $query->count();
        return self::successResult('',$list,$count);
}

   public function delete(){
        $id = request()->param('id');
        if (empty($id)) $this->error("请选择要删除的数据");
        $table = new \app\common\model\Goods();
        if (is_array($id)) {
            $id = implode(",", $id);
            $row = $table->whereIn('id', $id)->update(['is_del' => 1]);
        } else {
            $row = $table->where('id', $id)->update(['is_del' => 1]);
        }
        return $row ? self::successResult("成功") : self::errorResult("失败");
   }
  
   public function is_index()
   {
       $id = request()->param('id');
       $is_index = request()->param('is_index');
       if (empty($id)) $this->error("请选择要修改的数据");
       $table = new \app\common\model\Goods();
       $row = $table->where('id', $id)->update(['is_index' => $is_index]);
       return $row ? self::successResult() : self::errorResult('操作失败!请刷新后重试！');
   }
 
}
